package gam.t1.appraisal2.dinv.view.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import gam.t1.appraisal2.dinv.DataInventory;
import gam.t1.appraisal2.dinv.view.CollectionsView;
import gam.t1.appraisal2.dinv.view.SingleView;
import gam.t1.appraisal2.dinv.view.View2DCoordinate;
import org.bukkit.inventory.ItemStack;

import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public abstract class ClickBlockCollections<T extends CollectionsView<T>> implements CollectionsView<T> {
    private final Set<ClickBlock<T>> blocks;
    protected final DataInventory handler;
    private View2DCoordinate coordinate;
    public ClickBlockCollections(DataInventory handler) {
        blocks = Sets.newLinkedHashSet();
        this.handler = handler;
    }

    public ClickBlock<T> getClickBlock(int in){
        Iterator<ClickBlock<T>> v1 = blocks.iterator();
        while (v1.hasNext()) {
            ClickBlock<T> v2 = v1.next();
            if (v2.getIndex() == in) return v2;
        }
        return null;
    }

    @Override
    public void setCoordinate(View2DCoordinate coordinate) {
        this.coordinate = coordinate;
    }

    @Override
    public View2DCoordinate getCoordinate() {
        return coordinate;
    }

    @Override
    public int[] getIndex() {
        List<Integer> v1 = blocks.stream().map(ClickBlock::getIndex).collect(Collectors.toList());
        int[] v2 = new int[v1.size()];
        for (int i = 0; i < v2.length; i++) {
            v2[i] = v1.get(i);
        }
        return v2;
    }

    @Override
    public Map<Integer, ItemStack> getStorageStacks(CollectionsView<T> main) {
        Map<Integer, ItemStack> v1 = Maps.newHashMap();
        blocks.forEach(cB -> {
            ItemStack v2 = cB.getItemShowHandler().apply((T) main);
            if (v2 != null) {
                v1.put(cB.getIndex(), v2);
            }
        });
        return v1;
    }

    @Override
    public DataInventory getHandle() {
        return handler;
    }

    @Override
    public SingleView<T> register(int index, Predicate<T> clickhandler, Function<T, ItemStack> itemshowhandler) {
        ClickBlock<T> var = new ClickBlock<>();
        var.setIndex(index);
        var.setClickHandler(clickhandler);
        var.setItemShowHandler(itemshowhandler);
        var.setSys((T) this);
        var.setHandler(handler);
        blocks.add(var);
        return var;
    }
}
